<template>
    <base-card>

        <el-form ref="ruleFormRef" :model="formItem" style="  --el-text-color-placeholder: #999999;" :rules="rules"
            label-width="auto">
            <div class="topPackage">
                <div class="topRectangle"></div>
                <span> {{ isEdit ? '修改机构信息' : '添加机构信息' }} </span>
            </div>
            <el-divider />
            <p>机构信息</p>

            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="机构编号">
                        123
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="机构名称" style="size: 13px;" prop="name">
                        <el-input v-model="formItem.name" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="机构图片" style="size: 13px; height: 40px; width: 100px;">
                        <el-upload class="avatar-uploader" :action="`${baseURL}/images/upload`" :show-file-list="false"
                            :on-success="handleAvatarSuccess">
                            <img v-if="formItem.image" :src="formItem.image" class="avatar"
                                style="width: 100px; height: 100px;" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row :gutter="24" style="margin-top: 20px;">
                <el-col :span="8">

                    <el-form-item label="联系人姓名">
                        <el-input v-model="formItem.contacts" placeholder="请输入" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="联系电话">
                        <el-input v-model="formItem.phone" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-top: 20px;">
                <el-col :span="16">
                    <el-form-item label="机构地址" prop="address">
                        <el-input v-model="formItem.address" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24" style="margin-top: 20px;">
                <el-col :span="16">
                    <el-form-item label="机构介绍">
                        <el-input v-model="formItem.intro" placeholder="请输入" type="textarea" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-divider />
            <el-form-item>

                <el-button type="primary" @click="submitForm">
                    {{ isEdit ? '保存修改' : '添加' }}
                </el-button>
                <el-button @click="goBack"> 返回</el-button>

            </el-form-item>
        </el-form>

    </base-card>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'; // 统一导入消息组件
// import { UploadProps } from 'element-plus'
import { addOrganizationsApi, updateOrganizationsApi, detailOrganizationsApi } from '../../api/organizations';
import { useRoute } from 'vue-router';
const route = useRoute();
const router = useRouter()
const rules = ref({
    name: [
        { required: true, message: '机构名称不能为空', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '机构地址不能为空', trigger: 'blur' },
    ],
})
const isEdit = ref(!!route?.params._id);
const ruleFormRef = ref()
const formItem = ref({});
const baseURL = import.meta.env.VITE_BASE_URL;
const handleAvatarSuccess = (
    res
) => {
    console.log(formItem.value.image);

    if (res.code == 200) {
        formItem.value.image = res.data;
    }
}

const goBack = () => {
    console.log('go back')
    router.back()
};
// function addItem() {
//     addOrganizations()
// }
onMounted(() => {
    if (isEdit.value) {
        getDetail();
        resetForm()
    }
})
// const toLogin = (formEl) => {
//     if (!formEl) return
//     formEl.validate((valid, fields) => {
//         if (valid) {

//             addOrganizations()

//             console.log('submit!')
//         } else {
//             console.log('error submit!', fields)
//         }
//     })
// }
async function addOrganizations() {

    const res = await addOrganizationsApi(formItem.value)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: '添加成功',

        })
        goBack()
    } else {
        ElMessage.error(res.message)
    }
}
// 编辑时：获取机构详情
async function getDetail() {
    const res = await detailOrganizationsApi({ _id: route.params._id });
    if (res.code == 200) {
        formItem.value = res.data; // 填充表单数据
    } else {
        ElMessage.error(res.message || '获取详情失败');
    }
}
async function submitForm() {
    if (!ruleFormRef.value) return;

    ruleFormRef.value.validate(async (valid) => {
        if (!valid) return;

        try {
            let res;
            const formData = { ...formItem.value };

            if (isEdit.value) {
                // 编辑模式需要携带_id
                res = await updateOrganizationsApi({
                    ...formData,
                    _id: route.params._id
                });
            } else {
                // 添加模式必须移除_id字段（如果存在）
                delete formData._id;
                res = await addOrganizationsApi(formData);
            }

            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '修改成功' : '添加成功'
                });
                goBack();
            } else {
                ElMessage.error(res.message || '操作失败');
            }
        } catch (error) {
            ElMessage.error('网络错误，请重试');
        }
    });
}

function resetForm() {
    isEdit.value = !!route.params._id;

    // 清空表单
    formItem.value = {
        name: '',
        address: '',
        contacts: '',
        phone: '',
        intro: '',
        image: ''
    };

    // 如果是编辑模式，加载机构详情
    if (isEdit.value) {
        getDetail();
    }
}

</script>

<style scoped>
.avatar-uploader .avatar {
    width: 30px;
    height: 30px;

    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 30px;
    height: 30px;
    text-align: center;
}

.topPackage {
    display: flex;

    span {
        font-weight: 500;
        font-style: normal;
        font-size: 18px;
        color: rgba(51, 51, 51, 0.898039215686275);

    }
}

.topRectangle {
    width: 6px;
    height: 20px;
    background: inherit;
    background-color: rgba(41, 132, 248, 1);
    border: none;
    border-radius: 8px;
    margin-right: 20px;
}
</style>